package com.ruoyi.system.config;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.system.domain.PTask;
import com.ruoyi.system.service.IPTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint("/ws")
@Component
public class WebSocketServer {
    // 日志对象
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    // concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    private static AtomicInteger onlineNum = new AtomicInteger();
    /*
     * 客户端创建连接时触发
     * */
    @OnOpen
    public void onOpen(Session session) {
        sessionPools.put("1", session);
        addOnlineCount();
        log.info("websocket连接成功");
        IPTaskService bean = SpringUtil.getBean(IPTaskService.class);
        QueryWrapper<PTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status","0");
        Map<String, Object> jsonResult = new HashMap<>();
        jsonResult.put("dypass", bean.list(queryWrapper));
        sendInfo("1", JSONUtil.toJsonStr(jsonResult));

    }

    /**
     * 客户端连接关闭时触发
     **/
    @OnClose
    public void onClose() {
        sessionPools.remove("1");
        subOnlineCount();
        log.info("连接关闭");
    }

    /**
     * 接收到客户端消息时触发
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        if (!"ping".equals(message)) {
            log.info("收到来自客户端的消息:" + message);
        }else{
            log.info("收到心跳:{}" , message);
            sendInfo("1", "pong");
        }
    }

    /**
     * 连接发生异常时候触发
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    // 给指定用户发送信息
    public void sendInfo(String userId, String message) {
        Session session = sessionPools.get(userId);
        try {
            sendMessage(session, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
                session.getAsyncRemote().sendText(message);
            }
        }
    }

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }
    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

    public static AtomicInteger getOnlineNumber() {
        return onlineNum;
    }

    public static ConcurrentHashMap<String, Session> getSessionPools() {
        return sessionPools;
    }

}
